package com.bitcat.todoapp.demo.newslistdemo

import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bitcat.todoapp.databinding.ItemNewsBinding
import com.bitcat.todoapp.demo.netdemo.New
import com.bumptech.glide.Glide

class NewsAdapter(private val list: MutableList<New>) :
    RecyclerView.Adapter<NewsAdapter.NewsViewHolder>() {


    // ViewHolder 缓存item视图
    class NewsViewHolder(val binding: ItemNewsBinding) : RecyclerView.ViewHolder(binding.root)


    //作用：创建ViewHolder
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NewsViewHolder {
        Log.d("调试", "onCreateViewHolder: 调用了")
        val binding = ItemNewsBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return NewsViewHolder(binding)
    }

    //作用：返回item数量
    override fun getItemCount(): Int = list.size


    // 作用：绑定数据
    override fun onBindViewHolder(holder: NewsViewHolder, position: Int) {
        Log.d("调试", "onBindViewHolder: 位置：${position} 调用了")
        // 获取当前item的数据
        val newItem = list[position]

        holder.binding.titleTextView.text = newItem.title
        holder.binding.contentTextView.text = newItem.hint

        //Glide
        Glide
            .with(holder.itemView.context)
            .load(newItem.thumbnail)
            .into(holder.binding.newsImageView)

    }

    fun updateNews(news: List<New>) {
        list.clear()
        list.addAll(news)
        notifyDataSetChanged() //提醒数据发生了变化，需要更新界面
    }
}